package com.tgy.leetcode;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
 */
public class _783_二叉搜索树节点最小距离 {

    public static int minDiffInBST(TreeNode root) {

        if (root == null || (root.left == null && root.right == null)) {
            return 0;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        TreeNode preNode = null;
        int ret = Integer.MAX_VALUE;

        while (true) {

            while (node != null) {

                stack.push(node);
                node = node.left;
            }

            if (stack.isEmpty()) {

                break;
            }

            node = stack.pop();

            if (preNode != null) {

                ret = Math.min(ret,Math.abs(node.val - preNode.val));
            }

            preNode = node;
            node = node.right;
        }

        return ret;
    }


}
